import moment from 'moment';
import common from "./check-common";
import React from 'react';
import {Row, Col, Button, Radio, Alert, Checkbox, Steps, Divider, Icon, Select, Dropdown, Menu} from 'antd';
import {messages} from "share/common";
import IndirectUpload from 'containers/financial-management/check-center/indirect-upload';
import config from "config";
import AdvanceTable from 'components/advanced-table';
import Control from 'components/control'

export default {

  searchFormDefault(type) {
    const FORM_OPTION_DEFAULT = {
      air: ['vendorName','approvalDate','journeyId','passengerName'],
      hotel: ['vendorName','approvalDate','journeyId','clientNames'],
      train: ['vendorName','approvalDate1','journeyId','passengerName'],
      yget: ['vendorName','approvalDate','recordId'],
      car: ['vendorName','payDate','journeyId'],
      dining: ['vendorName','orderDate','journeyId'],
    }
    return FORM_OPTION_DEFAULT[type];
  },

  checkCenterTable(context) {
    const {state} = context;
    const {columns, type, serverColumns} = state;
    if(serverColumns.length) {
      const source = this.getSourceByColumns(serverColumns, columns);
      const finalColumns = this.handleColumns(source, context)
      return this.checkCenterTableNext(context, finalColumns);
    }
  },

  //根据外部传入的columns更新source，主要是增删列的更新
  getSourceByColumns(source, columns) {
    //如果columns中没有source中有的列，则为删除对应列，设置deleted为true
    let target = source.map(s => {
      let item = columns.find(c => c.dataIndex === s.columnName);
      if(!item)
        s.deleted = true;
      return s;
    });
    let maxSequence = 0;
    columns.map(c => maxSequence = Math.max(maxSequence, c.sequence || 0));
    if(typeof maxSequence !== 'number')
      maxSequence = 0;
    //如果source中没有columns中有的列，则为增加对应列，增加到最后
    columns.map(c => {
      let item = source.find(s => s.columnName === c.dataIndex);
      if(!item)
        target.push({
          columnName: c.dataIndex,
          hide: false,
          width: (typeof c.width === 'number' && c.width) || 150,
          sequence: ++maxSequence,
          fixed: null
        });
    });
    return target;
  },

  handleColumns(source, context) {
    const {state} = context;
    const {columns} = state;
    let result = [];
    let sortedData = source.sort((a, b) => a.sequence - b.sequence);
    sortedData.map(item => {
      let column = columns.find(c => c.dataIndex === item.columnName);
      if(column) {
        result.push({ ...column, hide: item.hide, width: item.width });
      }
    });
    return result;
  },

  checkCenterTableNext(context, finalColumns) {
    const {state, advanceTableServer, advanceTableRef, advanceTableFooter, advanceTableOnGetData, isTheSameResult} = context;
    const {loading, data, columns, pagination, rowSelection, offLineCheckModel, type, checkOffLineResultArray} = state;
    const {searchForm, offColumns, checkOffLineResult} = state;
    const showData = offLineCheckModel ? checkOffLineResultArray || [] : data;
    const baseOption = {
      // rowSelection: rowSelection,
      service: advanceTableServer,
      index: true,
      onRef: advanceTableRef,
      // footer: advanceTableFooter(),
      rowKey: record => record.recordId,
      onGetData: advanceTableOnGetData,
    }
    // todo  是否设置默认值？
    const defaultList = false ? this.searchFormDefault(type) : [];
    const option = Object.assign({}, {
      columns: finalColumns,
      // searchForm: searchForm,
      tableName: `onLineTableCenter${type}`,
      pinnedList: defaultList,
      title: messages('financial-management.key932')/*常用查询条件*/
    }, baseOption);

    const offOption = Object.assign({}, {columns: offColumns, tableName: `offLineTableCenter${type}`}, baseOption);

    if (finalColumns.length > 0 && !offLineCheckModel) {
      return (
        <AdvanceTable
          key='on'
          {...option}
        />
      )
    } else if (offColumns.length > 0) {
      return (
        <AdvanceTable
          key='off'
          {...offOption}
        >
          {
            checkOffLineResult.importTotal && (
              <div style={{margin:'0 12px 12px -20px'}}>
                <span style={{fontWeight: 'bold'}}>{messages('financial-management.key694')/*核对结果*/}</span>:&nbsp;&nbsp;
                <div style={{display: 'inline-block'}}>
                  <Checkbox.Group onChange={isTheSameResult}>
                    <Checkbox value='1'>{messages('financial-management.key699')/*一致*/}</Checkbox>
                    <Checkbox value='2'>{messages('financial-management.key700')/*不一致*/}</Checkbox>
                  </Checkbox.Group>
                </div>
              </div>
            )
          }
        </AdvanceTable>
      )
    }
  },

  renderMoreSelect(onMoreOperator, dis) {
    const moreMenu = (
      <Menu onClick={onMoreOperator}>
        <Menu.Item key="cancelMark">{messages('financial-management.key862')/*取消标记*/}</Menu.Item>
      </Menu>
    )
    return (
      <Dropdown.Button
        disabled={dis}
        placement="topRight"
        onClick={() => onMoreOperator({key: 'addMark'})}
        overlay={moreMenu}
        icon={<Icon type="up" />}
      >
        {messages('financial-management.key863')/*增加标记*/}
      </Dropdown.Button>
    )
  },

  uploadResult(context) {
    const {state, downloadCheckResult} = context;
    const {checkOffLineResult} = state;
    if (checkOffLineResult.importTotal)
      return (
        <div>
          <h3>{messages('financial-management.key694')/*核对结果*/}</h3>
          <div style={{margin: 24}}>
            <Icon type="check-circle" style={{color: "#52c41a"}}/>
            <span>{messages('financial-management.key695', {arg1: checkOffLineResult.importTotal})/*共导入{arg1}条数据*/}，{messages('financial-management.key696', {arg1: checkOffLineResult.matchingTotal})/*{arg1}条完全一致*/}。</span>
            <a onClick={downloadCheckResult}>{messages('financial-management.key697')/*下载核对结果*/}></a>
          </div>
          <Alert
            className='alert-error'
            type="info"
            message={messages('financial-management.key698')/*您可以批量确认核对结果一致的数据*/}
            showIcon
          />
        </div>
      )
  },

  uploadSteps(context) {
    const {props, state, startOffLine, downloadOffLineTemplate, handleUpload, finishUpload} = context;
    const {uploading, searchParams, type, checkOffLineResult} = state;
    const {company} = props;
    const searchData = {
      companyType: searchParams.companyType,
      [`${type}Request`]: searchParams,
    };
    const params = {request: JSON.stringify(searchData)};
    const url = `${config.baseUrl}/vendor-data-service/api/order/reconciliation/contrast?companyOID=${company.companyOID}`
    const stepStyle = {
      width: 120,
      whiteSpace: 'normal',
      lineHeight: 1.2,
    }
    return (
      <div>
        <Button
          style={{margin: '12px 0'}}
          onClick={() => startOffLine(true)}
        >
          {messages('financial-management.key701')/*退出核对模式*/}
        </Button>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        {
          !checkOffLineResult.importTotal &&
          <Alert
            className='alert-error'
            type="info"
            message={messages('financial-management.key786')/*导入模板将与满足筛选条件的数据进行核对。*/}
            showIcon
          />
        }
        <Steps style={{padding: '40px 24px', width: '92%'}}>
          <Steps.Step
            key='1'
            title={messages('components.key483'/*下载模板*/)}
            description={
              <Button
                onClick={downloadOffLineTemplate}
                icon='download'
              >
                {messages('components.key483'/*下载模板*/)}
              </Button>
            }
          />
          <Steps.Step
            className='ant-steps-item-process'
            key='2'
            title={
              <p style={stepStyle}>
                {messages('financial-management.key702')/*将消费商账单贴入模板内并上传*/}
              </p>
            }
            description={
              <IndirectUpload
                style={{marginTop: -8}}
                uploadUrl={url}
                params={params}
                isUpload={uploading}
                finishUpload={finishUpload}
              />
            }
          />
          <Steps.Step
            className='ant-steps-item-process'
            key='3'
            title={messages('financial-management.key703')/*核对*/}
            description={
              <Button
                onClick={handleUpload}
              >
                {messages('financial-management.key704')/*开始核对*/}
              </Button>}
          />
          <Steps.Step
            className='ant-steps-item-process'
            key='4'
            title={
              <p style={stepStyle}>
                {messages('financial-management.key924')/*确认无误后，可批量确认数据*/}
              </p>
            }
          />
        </Steps>
      </div>
    )
  },

  statusTabRow(context) {
    const {onRadioChange, startOffLine, state} = context;
    const {defaultLabel, radio, searchParams} = state;
    const {type} = context.props.params;
    return (
      <Row type="flex" justify="space-between" align="middle" style={{marginTop: 12}}>
        <Col span={8}>
          <Radio.Group
            defaultValue={defaultLabel}
            className="check-center-radio"
            onChange={onRadioChange}
            style={{marginBottom: 16}}
          >
            {radio.map((item) => <Radio.Button key={item.label} value={item.value}>{item.label}</Radio.Button>)}
          </Radio.Group>
        </Col>
        <Col span={12}/>
      </Row>
    )
  },

  getOperatorRow(context) {
    const {showConfirmBill, buttonRoleSwitch, offLineCheckModel, pagination, selectedData, searchParams} = context.state;
    const {amount} = context.state;
    const {openUploadOffLineData, showImport, downloadBill, startOffLine, props} = context;
    const inlineBox = {
      margin: '0 16px 6px 0'
    }
    const {type} = context.props.params;
    return (
      <div>
        <Row>
          <Col span={8}>
            {false && !offLineCheckModel &&
            <div className='amount'>
              <span>{common.getRadioMap(searchParams.reconciliationStatus)}</span>
              <Divider type="vertical"/>
              <span>{messages('common.amount')/*"金额"*/}</span> : CNY <span
              className='value-number'>{common.formatCurrency(amount)}</span>
              <Divider type="vertical"/>
              <span>{messages('financial-management.key683')/*笔数*/}</span> : <span
              className='value-number'>{pagination.total} {messages('financial-management.key211')/*笔*/}</span>
            </div>
            }
          </Col>
          <Col span={16} style={{textAlign: 'right'}}>
            {showConfirmBill && (
              <Control>
                <div style={{display: 'inline-block'}} data-control="check-center.hidden">
                  {
                    (type === 'air' || type === 'hotel' || type === 'car') && (
                      <Button onClick={() => openUploadOffLineData(true)}>{messages('financial-management.key864')/*导入线下消费数据*/}</Button>
                    )
                  }
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  {/*{*/}
                    {/*searchParams.reconciliationStatus === '2' && type !== 'dining' &&*/}
                    {/*<Button onClick={() => startOffLine(false)}>{messages('financial-management.key705')/*线下账单核对*!/</Button>*/}
                  {/*}*/}
                  {/*&nbsp;&nbsp;&nbsp;&nbsp;*/}
                  {/*<Button*/}
                    {/*style={inlineBox}*/}
                    {/*onClick={() => showImport(true)}*/}
                  {/*>*/}
                    {/*{messages('financial-management.key706')/*批量确认*!/*/}
                  {/*</Button>*/}
                </div>
              </Control>
            )
            }
            <div style={{display: 'inline-block'}}>
              <Button type='primary' style={inlineBox} onClick={downloadBill}>
                {messages('financial-management.key865')/*导出账单*/}
              </Button>
            </div>
          </Col>
        </Row>
      </div>
    )
  },

  /**
   * 搜所表单事件触发处理函数
   * @param value  搜所表单值
   * @param event  事件对象
   * @param formRef 表单实例
   * @returns {boolean} 是否已处理
   * (订单中心也使用该方法)
   */
  handleEventDictionary(value, event, formRef) {
    let date = new Date();
    if (this.getHandleEvent()[value]) {
      let labelS = this.getHandleEvent()[value].labelS;
      let labelE = this.getHandleEvent()[value].labelE;
      switch (event) {
        case 'today':
          formRef.setValues({[labelS]: new Date(), [labelE]: new Date()});
          break;

        case 'oneMonth':
          formRef.setValues({
            [labelE]: new Date(),
            [labelS]: `${new Date().format('yyyy-MM')}-01`,
          });
          break;

        case 'threeMonths':
          formRef.setValues({
            [labelE]: new Date(),
            [labelS]: new Date(date.setMonth(date.getMonth() - 3)).format('yyyy-MM-dd')
          });
          break;

        case 'year':
          let preYear = common.getNextYear(moment(new Date()).format('YYYY-MM-DD'));
          formRef.setValues({[labelE]: new Date(), [labelS]: preYear});
          break;

        case 'all':
          formRef.setValues({[labelE]: null, [labelS]: null});
          break;
      }
      return true;
    }
    return false;
  },

  /**
   * 搜所区定义事件名称以及事件对应的关键字ID
   * @returns
   */
  getHandleEvent() {
    const eventId = {
      CHANGETIME: {
        labelS: 'start',
        labelE: 'end',
      },
      CHANGETIME_ORDERCENTER: {
        labelS: 'dateFrom',
        labelE: 'dateTo',
      }
    }
    return eventId;
  },

}
